#!/usr/bin/env node

const axios = require('axios');
const chalk = require('chalk');
const xlsx = require('node-xlsx');
const { program } = require('commander');
const package = require('./package.json');
let extensions, adcode, quote, ip;

program
    .name('Weather Query')
    .description('A command line tool of live weather in China.')
    .option('-f, --forecast', 'get weather forecast')
    .version(package.version, '-v, --version', 'output the current version')
    .on('--help', () => {
        console.log();
        console.log(chalk.gray('Examples：'));
        console.log(chalk.blueBright('  $'), 'w | weather');
        console.log(chalk.blueBright('  $'), 'w 省|市|区');
        console.log(chalk.blueBright('  $'), 'w -f 省|市|区');
        console.log(chalk.blueBright('  $'), 'weather 省|市|区');
        console.log(chalk.blueBright('  $'), 'weather -f 省|市|区');
    });
program.parse(process.argv);

program.opts().forecast === true ? (extensions = 'all') : (extensions = 'base');

if (process.argv.length < 3) {
    getIP()
        .then(() => getCity())
        .then(() => getQuote())
        .then(() => getAdcode())
} else {
    process.argv[2] === '-f' || process.argv[2] === '--forecast' ? (city = process.argv[3]) : (city = process.argv[2]);
    getQuote()
        .then(() => {
            getAdcode();
        });
}

function getQuote() {
    const url = `https://v1.hitokoto.cn/?c=i&c=k`;
    return new Promise((resolve, reject) => {
        axios
            .get(url, {
                timeout: 5000,
            })
            .then((res) => {
                quote = res.data.hitokoto;
                resolve(quote);
            })
            .catch((err) => reject(err));
    });
}

function getWeather() {
    const key = 'bc8571febb40caaa4870a0788438c02b';
    const url = `https://restapi.amap.com/v3/weather/weatherInfo`;
    axios
        .get(url, {
            params: {
                city: adcode,
                key: key,
                extensions: extensions,
                output: 'JSON',
            },
            timeout: 5000,
        })
        .then((res) => {
            if (extensions === 'base') {
                const lives = res.data.lives[0];
                console.log();
                console.log(chalk.green(city));
                console.log();
                console.log(chalk.green(`天气 ${lives.weather}`));
                console.log(chalk.green(`气温 ${lives.temperature}`));
                console.log(chalk.green(`风力 ${lives.windpower}`));
                console.log(chalk.green(`湿度 ${lives.humidity}`));
                console.log(chalk.green(`风向 ${lives.winddirection}`));
                console.log();
                console.log(chalk.green(`${lives.reporttime}`));
                console.log();
                console.log(chalk.green(`${quote}`));
                console.log();
            } else {
                const forecasts = res.data.forecasts[0];
                console.log();
                console.log(chalk.green(city));
                console.log();
                for (let cast of forecasts.casts) {
                    let date = cast.date.split('-');
                    let year = date[1][0] == '0' ? date[1][1] : date[1];
                    let day = date[2][0] == '0' ? date[2][1] : date[2];
                    console.log(chalk.green(year + '/' + day, cast.dayweather, `${cast.daytemp}`));
                }
                console.log();
                console.log(chalk.green(`${forecasts.reporttime}`));
                console.log();
                console.log(chalk.green(`${quote}`));
                console.log();
            }
        })
        .catch((err) => {
            console.log(err);
        });
}

function getIP() {
    const url = `https://www.taobao.com/help/getip.php`;
    return new Promise((resolve, reject) => {
        axios
            .get(url, {
                timeout: 5000,
            })
            .then((response) => {
                ip = response.data.match(/\d.*\d/)[0];
                resolve(ip);
            })
            .catch((err) => {
                reject(err);
            });
    });
}

function getCity() {
    let key = 'ec3dd6d7c35413cbe888551e8f7916d0';
    let type = 4;
    let url = `https://restapi.amap.com/v5/ip?key=${key}&type=${type}&ip=${ip}`;
    return new Promise((resolve, reject) => {
        axios
            .get(url, {
                timeout: 5000,
            })
            .then((response) => {
                city = response.data.district;
                resolve(city);
            })
            .catch((err) => {
                reject(err);
            });
    });
}

function getAdcode() {
    const sheets = xlsx.parse(__dirname + '/doc/AMap_adcode_citycode_20210406.xlsx');
    try {
        sheets.forEach((sheet) => {
            sheets[0]['data'].forEach((item, index) => {
                if (item[0] === city) {
                    adcode = item[1];
                    getWeather();
                    throw new Error();
                }
                if (index == sheet.data.length - 1) {
                    console.log('未知城市');
                }
            });
        });
    } catch (err) {}
}